package com.fruit.service.user.impl;


import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fruit.constants.UserConstant;
import com.fruit.mapper.user.UserMapper;
import com.fruit.pojo.order.OrderGood;
import com.fruit.pojo.user.Follow;
import com.fruit.pojo.user.Region;
import com.fruit.pojo.user.Address;
import com.fruit.pojo.user.ComAccount;
import com.fruit.pojo.user.SupplierReal;
import com.fruit.pojo.user.UserAccount;
import com.fruit.pojo.user.UserInfo;
import com.fruit.pojo.user.UserLogin;
import com.fruit.service.sms.SmsCodeManager;
import com.fruit.service.user.UserManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.MD5Util;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;
import com.fruit.util.ValidateUtils;

@Service("userService")
public class UserService implements UserManager {

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private SmsCodeManager smsCodeService;
	
	
	
	
	@Override
	public UserLogin getUserLoginById(int loginId) {
		return userMapper.getUserLoginById(loginId);
	}

	@Override
	public UserLogin getUserLoginByUserName(String userName) {
		return userMapper.getUserLoginByUserName(userName);
	}

	@Override
	public UserInfo getUserInfoByLoginId(int loginId) {
		return userMapper.getUserInfoByLoginId(loginId);
	}

	@Override
	public Map<String, Object> getRegisterValidate(UserLogin ul) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		//验证参数是否合法
		String userName = ul.getUserName();
		if(!ValidateUtils.phone(userName)){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "phone_error", "手机号码格式错误!"));
			return resMap;
		}
		String pwd = ul.getPwd();
		if(!ValidateUtils.password(pwd)){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "pwd_empty", "密码需6-20位数字和字母组成!"));
			return resMap;
		}
		
		String code = ul.getCode();
		if(!ValidateUtils.code(code)){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_empty", "验证码不能为空!"));
			return resMap;
		}
		
		String inviteCode = ul.getInviteCode();
		if(!ValidateUtils.inviteCode(inviteCode)){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "inviteCode_empty", "邀请码格式错误!"));
			return resMap;
		}
		
		//判断用户是否存在
		UserLogin login = userMapper.getUserLoginByUserName(userName);
		
		if(login != null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "phone_exists", "手机号码已存在!"));
			return resMap;
		}
		
		String msg = smsCodeService.getValidateCode(ul.getUserName(), ul.getCode(), "register");
		if(StringUtils.equals(msg, "expire")){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_expire", "验证码已失效!"));
			return resMap;
		}else if(!StringUtils.equals(msg, "ok")){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_error", "验证码有误!"));
			return resMap;
		}
		
		//验证邀请码是否存在以及是否已使用
		SupplierReal sr = new SupplierReal();
		sr.setInviteCode(ul.getInviteCode());
		sr.setAuditState(UserConstant.SUPPLIER_AUDIT_CHECKED);
		sr = userMapper.getSupplierByInviteCode(sr);
		if(sr == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "inviteCode_no_expire", "邀请码不存在!"));
			return resMap;
		}
		if(StringUtils.equals(sr.getIsUseInviteCode(), "01")){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "inviteCode_expire", "邀请码已失效!"));
			return resMap;
		}
		
		resMap.put("sr", sr);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "验证成功"));
		return resMap;
	}

	
	
	@Override
	public Map<String, Object> updatePwd(UserLogin ul) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		//验证参数是否合法
		String userName = ul.getUserName();
		if(!ValidateUtils.phone(userName)){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "phone_error", "手机号码格式错误!"));
			return resMap;
		}
		String pwd = ul.getPwd();
		if(!ValidateUtils.password(pwd)){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "pwd_empty", "密码需6-20位数字和字母组成!"));
			return resMap;
		}
		
		String code = ul.getCode();
		if(!ValidateUtils.code(code)){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_empty", "验证码不能为空!"));
			return resMap;
		}
		//判断用户是否存在
		UserLogin login = userMapper.getUserLoginByUserName(userName);
				
		if(login == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "phone_exists", "手机号码不存在!"));
			return resMap;
		}		
		
		String msg = smsCodeService.getValidateCode(ul.getUserName(), ul.getCode(), "updatepwd");
		if(StringUtils.equals(msg, "expire")){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_expire", "验证码已失效!"));
			return resMap;
		}else if(!StringUtils.equals(msg, "ok")){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_error", "验证码有误!"));
			return resMap;
		}
		
		ul.setPwd(MD5Util.MD5Encode(ul.getPwd(), "utf-8"));
		userMapper.updateUserPwd(ul);
		
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "密码设置成功!"));
		
		return resMap;
	}

	@Override
	public Map<String, Object> saveUserRegister(UserLogin login, SupplierReal sr) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		int res = 1;
		try {
			int num = 0;
			login.setPwd(MD5Util.MD5Encode(login.getPwd(), "utf-8"));
			userMapper.saveUserLogin(login);
			UserInfo user = new UserInfo();
			user.setCodePre(DateUtil.getYear());
			user.setCodeSuf(CustomUtil.buildRandom(3) + "");
			user.setLoginId(login.getId());
			user.setPhone(login.getUserName());
			String petName = CustomUtil.subPhone(user.getPhone());
			user.setPetName(petName);
			user.setCompanyName(sr.getBusName());
			user.setAddress("");
			user.setCreationDate("");
			user.setIsAuthentication("01");
			userMapper.saveUserInfo(user);
			UserAccount account = new UserAccount();
			account.setUserId(user.getId());
			account.setLoginId(login.getId());
			account.setBalance(new BigDecimal(0));
			account.setPoints(new BigDecimal(0));
			userMapper.saveUserAccount(account);
			sr.setUserId(user.getId());
			num = userMapper.updateSupplierRealUse(sr);
			if(num == 0){
				res = 0;
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "faile", "注册失败"));
				return resMap;
			}
			
			UserInfo userInfo = userMapper.getUserById(user.getId());
			resMap.put("user", userInfo);
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "注册成功"));
			return resMap;
		} finally {
			if(res == 0){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}

		
	}

	@Override
	public List<Address> getAddressList(Map<String, Object> parame) {
		return userMapper.getAddressList(parame);
	}

	@Override
	public void saveAddress(Address address) {
		userMapper.saveAddress(address);
	}

	@Override
	public void updateAddress(Address address) {
		userMapper.updateAddress(address);
	}

	@Override
	public void deleteAddress(int id) {
		userMapper.deleteAddress(id);
	}

	@Override
	public Address getAddress(int id) {
		return userMapper.getAddress(id);
	}

	@Override
	public List<Region> regionList(int id) {
		return userMapper.regionList(id);
	}

	@Override
	public UserInfo getUser(int userId) {
		UserInfo user= userMapper.getUserById(userId);
		if(user != null){
			if(user.getSex() != null){
				if("00".equals(user.getSex())){
					user.setSex("女");
				}else if("01".equals(user.getSex())){
					user.setSex("男");
				}
			}
		}
		 return user;
	}

	@Override
	public void updateUserMess(UserInfo user) {
        if (user.getPetName() != null && user.getPetName() != "") {
            userMapper.updateUserPetName(user);
            return;
        }
        if (user.getSex() != null && user.getSex() != "") {
        	if("女".equals(user.getSex())){
        		user.setSex("00");
        	}else if("男".equals(user.getSex())){
        		user.setSex("01");
        	}
            userMapper.updateUserSex(user);
        }
	}

	@Override
	public void updateUserHeadImage(UserInfo user) {
		userMapper.updateUserHeadImage(user);
	}

	@Override
	public void saveFollow(Follow follow) {
		follow.setCreateTime(DateUtil.getTime());
		userMapper.saveFollow(follow);
	}

	@Override
	public List<OrderGood> getFollowList(Map<String, Object> parame) {
		return userMapper.getFollowList(parame);
	}

	@Override
	public void deleteFollow(Follow follow) {
		userMapper.deleteFollow(follow);
	}

	@Override
	public void updateAddStatus(Address addre) {
		userMapper.updateAddStatus(addre);
	}

	@Override
	public int getFollowNum(Follow follow) {
		return userMapper.getFollowNum(follow);
	}

	@Override
	public ComAccount getContact() {
		return userMapper.getContact();
	}

}
